/**
 * Created by lixia on 2017/7/11.
 */
layui.config({
    base: "../static/akt-ui/js/"
});
var tools
layui.use(["laypage", "layer", "validator", "tools", "form"], function() {
    var $ = layui.jquery;
    var layer = layui.layer;
    tools = layui.tools;

    //签入
    $("#signInBtn").on("click", function(){
        layer.open({
            title: "坐席签入",
            type: 2,
            shadeClose: false,
            shade: 0.5,
            area: ["420px", "300px"],
            anim: 3,
            content: "soft-phone/checkIn",
            btn: ["签入", "关闭"],
            yes: function(index, layero) {
                var body = layer.getChildFrame("body", index);
                var param = tools.formToJson(body.find("form"));
                if(signIn(param)) {
                    layer.close(index);
                }
            }
        });
    });

    //签出
    $("#signOutBtn").on("click", function() {
        layer.open({
            title: "操作确认",
            content: "是否确认签出？",
            btn: ["确认", "取消"],
            yes: function (index, layero) {
                if(signOut()){
                    layer.close(index);
                }
            }
        });
    });

    //就绪
    $("#readyBtn, #statusMenuReadyBtn").on("click", function() {
        ready();
    });

    //置忙
    $("#notReadyBtn").on("click", function() {
        notReady();
    });

    //小休
    $("#restBtn").on("click", function() {
        rest();
    });

    //培训
    $("#trainBtn").on("click", function() {
        train();
    });

    //就餐
    $("#mealBtn").on("click", function() {
        meal();
    });

    //接听
    $("#acceptPhoneBtn").on("click", function() {
        answer();
    });

    //挂断
    $("#releasePhoneBtn").on("click", function() {
        release();
    });

    //保持
    $("#holdPhoneBtn").on("click", function() {
        hold();
    });

    //恢复
    $("#recoveryPhoneBtn").on("click", function() {
        held();
    });

    //内线拨号
    $("#dailPhoneInBtn").on("click", function(){
        layer.open({
            title: false,
            type: 2,
            shadeClose: false,
            shade: 0,
            area: ["320px", "580px"],
            anim: Math.floor(Math.random() * 7),
            content: "soft-phone/dialPage?type=in"
        });
    });

    //外线拨号
    $("#dailPhoneOutBtn").on("click", function(){
        layer.open({
            title: false,
            type: 2,
            shadeClose: false,
            shade: 0,
            area: ["320px", "580px"],
            anim: Math.floor(Math.random() * 7),
            content: "soft-phone/dialPage?type=out"
        });
    });

    //中梦拨号
    $("#dailPhoneZMBtn").on("click", function(){
        layer.open({
            title: false,
            type: 2,
            shadeClose: false,
            shade: 0,
            area: ["320px", "580px"],
            anim: Math.floor(Math.random() * 7),
            content: "soft-phone/dialPage?type=zm&callPrefix=06"
        });
    });

    //大都会拨号
    $("#dailPhoneDDHBtn").on("click", function(){
        layer.open({
            title: false,
            type: 2,
            shadeClose: false,
            shade: 0,
            area: ["320px", "580px"],
            anim: Math.floor(Math.random() * 7),
            content: "soft-phone/dialPage?type=ddh&callPrefix=04"
        });
    });

    //内线转接
    $("#transferPhoneInBtn").on("click", function(){
        layer.open({
            title: false,
            type: 2,
            shadeClose: false,
            shade: 0,
            area: ["320px", "660px"],
            anim: Math.floor(Math.random() * 7),
            content: "soft-phone/transfer?type=in"
        });
    });

    //转接医生助理组
    $("#skillGroupZLBtn").on("click", function(){
        transferSkillGroup("kefu");
    });

    //转接电话医生组
    $("#skillGroupYSBtn").on("click", function(){
        transferSkillGroup("kefu2");
    });

    //转接服务评分组
    $("#skillGroupPFBtn").on("click", function(){

    });

    //专属拨号
    $("#dailPhoneExclusiveBtn").on("click", function(){
        layer.open({
            title: "专属客户列表",
            type: 2,
            shadeClose: false,
            shade: 0,
            area: ["70%", "70%"],
            anim: Math.floor(Math.random() * 7),
            content: "vip/list"
        });
    });

    //外线转接
    $("#transferPhoneOutBtn").on("click", function(){
        layer.open({
            title: false,
            type: 2,
            shadeClose: false,
            shade: 0,
            area: ["320px", "660px"],
            anim: Math.floor(Math.random() * 7),
            content: "soft-phone/transfer?type=out"
        });
    });

    //内线会议
    $("#conferencePhoneInBtn").on("click", function(){
        layer.open({
            title: false,
            type: 2,
            shadeClose: false,
            shade: 0,
            area: ["320px", "660px"],
            anim: Math.floor(Math.random() * 7),
            content: "soft-phone/conference?type=in"
        });
    });

    //外线会议
    $("#conferencePhoneOutBtn").on("click", function(){
        layer.open({
            title: false,
            type: 2,
            shadeClose: false,
            shade: 0,
            area: ["320px", "660px"],
            anim: Math.floor(Math.random() * 7),
            content: "soft-phone/conference?type=out"
        });
    });

    //通话小结置忙
    $("#callSummaryForm #busy").on("click", function(){
        return parent.parent.setTimeSeconds(1);
    });

    //通话小结延长
    $("#callSummaryForm #extend").on("click", function(){
        return parent.parent.setTimeSeconds(120);
    });

});

/**
 * 展示主叫人信息
 * @param lastRecordId
 * @param customerNumber   主叫人手机号
 */
function  callerUserInfo(lastRecordId,customerNumber) {
    layer.open({
        title: "主叫人信息",
        type: 2,
        shadeClose: false,
        shade: 0.5,
        area: ["420px", "300px"],
        anim: 3,
        content: "/user/find/"+customerNumber,
        btn: ["新增工单", "关闭"],
        yes: function(index, layero) {
            var body = layer.getChildFrame("body", index);
            var param = tools.formToJson(body.find("form"));
            layer.close(index);
            addWorkOrder(lastRecordId,param);
        }
    });
}
function addWorkOrder(lastRecordId,params) {
    if(!params.extension){
        layer.msg("分机号不能为空！");
        return false;
    }
    layer.open({
        type:1,
        title:"添加工单",
        skin:"myclass",
        area:["50%"],
        content: $("#add").html(),
        btn: ["新增", "关闭"],
        success:function (layero,index) {
            var form = layui.form;
            form.render();
            layero.addClass('layui-form');
            layero.find('.layui-layer-btn0').attr('lay-filter', 'fromContent').attr('lay-submit', '');//将按钮弄成能提交的
            $(layero).find('select[name=machineType]').html(valMachineType());
            form.on('select(machineTypeFilter)', function(data){
                changeSubject(layero);
                form.render();
            });
            form.on('select(addressFilter)', function(data){
                selectfloor(layero)
                form.render();
            });
            form.render();
            $(layero).find('input[name=email]').val(params.email);
        },
        yes: function(index, layero) {
            var body = layer.getChildFrame("body", index);
            var data ={
                "email":$(layero).find('input[name=email]').val(),
                "machineType":$(layero).find('select[name=machineType]').val(),
                "repaireSubject":$(layero).find('select[name=repaireSubject]').val(),
                "source":'1',
                "address":$(layero).find('select[name=address]').val(),
                "floor":$(layero).find('select[name=floor]').val(),
                "description":$(layero).find('input[name=description]').val()
            }
            // var param = tools.formToJson(body.find("#add_form"));
            data["lastRecordId"] = lastRecordId;
            add(data,layero,index);
        }
    });

}
// 给分类赋值
function valMachineType() {
    var htmlStr = "<option value=''>请选择...</option>";
    $.each(repaireSubject,function (name,value) {
        htmlStr += "<option value = '"+value.value+"'>"+value.text+"</option>";
    });
    return htmlStr;
}
function changeSubject(layero) {
    var _machineType = $(layero).find('select[name=machineType]').val();
    $.each(repaireSubject,function (name,value) {
        if(_machineType == value.value){
            var htmlStr = "";
            $.each(value.list,function(index,text){
                htmlStr += "<option value='"+text.id+"'>"+text.words+"</option>";
            });
            $(layero).find("select[name=repaireSubject]").empty();
            $(layero).find("select[name=repaireSubject]").html(htmlStr);
            return false;
        }
    })
}

function add(param,layero,index) {
    $.ajax({
        url:ctx+'/repaireInfo/add',
        type : 'POST',
        data:param,
        success:function (result) {
            var layer = layui.layer;
            var json = JSON.parse(result);
            if(json.code=='0'){
                layer.close(index);
            }else{
                layer.open({
                    title: '报错了'
                    ,content: json.msg
                });
            }

        },
        error:function (result) {
            var json = JSON.parse(result);
            var layer = layui.layer;
            layer.open({
                title: '报错了'
                ,content: json.msg
            });

        }
    });
}
/**
 * 弹屏方法
 * @param id 电话记录id
 * @param callId 电话id
 * @param agentId 工号
 * @param agentDn 分机号
 * @param beginTime 开始时间
 * @param callingNumber 主叫号码
 * @param calledNumber 被叫号码
 * @param callDirection 电话方向
 * @param customerId 客户id
 */
function popUpWindow(id, callId, agentId, agentDn, beginTime, callingNumber, calledNumber, callDirection, customerId, otherData){
    if(!customerId) {
        customerId = "-1";
    }
    var callerNumber = callingNumber;
    if(callDirection == "2"){
        callerNumber = calledNumber;
    }
    var tab = layui.tab();
    //关闭之前的弹屏
    $("#admin-body cite:contains('电话弹屏')").next().click();
    tab.tabAdd({
        title: "电话弹屏",
        icon: "&#xe623;",
        href: "./customer/popUpWindow?id=" + id + "&recordId=" + id + "&callId=" + callId + "&beginTime=" + beginTime + "&callingNumber="
            + callingNumber + "&calledNumber=" + calledNumber + "&callDirection=" + callDirection
            + "&customerId=" + customerId + "&agentDn=" + agentDn + "&userNo=" + agentId + "&callerNumber=" + callerNumber
    });

    //呼入显示热线名称
    if(callDirection == "1") {
        var lines = getLines();
        if(lines){
            $("#callingStatus").html(lines[calledNumber]).show();
        }
    }
}

/**
 * 电话接通
 * @param id
 * @param contactId  联络标识
 * @param ringingTime
 */
function established(id, contactId, ringingTime,agentId,customerNumber){
    $.ajax({
        type: "POST",
        url: ctx+"/tblCallSerial/insert",
        data: {
            lastRecordId: id,
            contactId:contactId,
            beginTime: ringingTime,
            agentId:agentId,
            callerNumber:customerNumber
        },
        dataType: "json",
        success: function(data){
            if(data.success){
                layer.msg("电话接通",{
                    zIndex: Math.MAX_VALUE
                });
            }
        }
    });
}

/**
 * 通话结束
 * @param id
 * @param callId
 * @param callTime
 */
function released(id, contactId, endTime,callDuration){
    $.ajax({
        type: "POST",
        url: ctx+"/tblCallSerial/update",
        data: {
            lastRecordId: id,
            contactId:contactId,
            callDuration: callDuration
        },
        dataType: "json",
        success: function(data){
            if(data.success){
                layer.msg("电话挂断",{
                    zIndex: Math.MAX_VALUE
                });
            }
        }
    });
}

/**
 * 获取热线列表
 */
function getLines(){
    var lines = window.sessionStorage.getItem("lines");
    lines = JSON.parse(lines);
    if(lines){
        return lines;
    } else {
        $.ajax({
            type: "get",
            url: "./line/getLines",
            async: false,
            dataType: "json",
            success: function (data) {
                data = eval(data);
                lines = data;
            }
        });

        window.sessionStorage.setItem("lines", JSON.stringify(lines));
        return lines;
    }
}